package com.jhd.fuzhou.view.login;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.LoginService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.AuthToken;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.UserMessage;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class LoginActivity extends BaseActivity {

    private Context context=LoginActivity.this;
    @BindView(R.id.et_username)EditText et_username;
    @BindView(R.id.et_password)EditText et_password;
    @BindView(R.id.btn_login)Button btn_login;
    @BindView(R.id.btn_register)Button btn_register;
    @BindView(R.id.tv_forget)TextView tv_forget;
    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void processLogic() {
        String username=application.getUserName();
        String password=application.getPassword();
        if(username!=null&&password!=null){
            et_username.setText(username);
            et_password.setText(password);
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager am= (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
            String packName=this.getPackageName();
            am.killBackgroundProcesses(packName);
        }
        return super.onKeyDown(keyCode, event);
    }
    @OnClick({R.id.btn_login,R.id.btn_register,R.id.tv_forget})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_login:
                if(et_username.getText().toString().equals("")||et_password.getText().toString().equals("")){
                    UtilHelper.alertMsg(context, "提示", "用户名和密码不能为空!");
                }else{
                    if(!et_username.getText().toString().trim().equals("admin")&&et_password.getText().toString().trim().equals("111111")){
                        UtilHelper.alertMsg3(context, "提示", "密码安全性太低，请修改密码!");
                    }else{
                        Login();
                    }
                }
                break;
            case R.id.btn_register:

                break;
            case R.id.tv_forget:
                startActivity(new Intent(context,ForgetPasswordActivity.class));
                break;
        }
    }

    private void Login(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("username",et_username.getText().toString()).addParam("password",et_password.getText().toString()).addParam("type","password");
        Call<JsonForResult> jsonForResultCall = vs.getAuthInfo(params);//调用接口获取json返回
        jsonForResultCall.enqueue(new LoginInfoCallback(et_username.getText().toString(), et_password.getText().toString()));
    }
    //登录的回调接口
    private class LoginInfoCallback implements Callback<JsonForResult> {
        private String _name;
        private String _password;
        public LoginInfoCallback(String name, String password) {
            _name = name;
            _password = password;
        }
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                if (response.code() > 400 && response.code() < 500) {
                    UtilHelper.alertMsg(context, "错误", "用户名或密码错误!");
                    return;
                }
                JsonForResult jsonForResult = response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    //请求授权信息
                    AuthToken authToken = JSON.parseObject(jsonForResult.getData().toString(), AuthToken.class);
                    if (authToken == null || StringUtil.isNullOrEmpty(authToken.getAccessToken())) {
                        UtilHelper.alertMsg(context, "错误", "请求授权信息失败");
                        return;
                    }
                    String accessToken = authToken.getAccessToken();
                    //String deptId = authToken.getAccessTokenByKey("deptId").toString();
                    application.setAccessToken(accessToken);
                    application.setUserId(authToken.getAccessTokenByKey("userId").toString());
                    application.setUserName(_name);
                    application.setPassword(_password);
                    //application.setDeptId(deptId);
                    getPersonInfo();
                } else {
                    String msg = "";
                    if (jsonForResult == null) msg = "登录失败";
                    else msg = jsonForResult.getMessage();
                    UtilHelper.alertMsg(context, "错误", msg);
                }
            } catch (Exception e) {
                UtilHelper.alertMsg(context, "错误", e.getMessage());
            }
        }
        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "登录失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) {
                if (t.getMessage().indexOf("400") >= 0) {
                    msg = "用户名或密码错误!";
                } else {
                    if(t.getMessage().contains("Failed to connect to")){
                        msg = msg +"网络错误";
                    }else{
                        msg=msg+t.getMessage();
                    }
                }
            }
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    private void getPersonInfo(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("sysUserId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getPersonInfo(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            UserMessage userMessage=JSON.parseObject(jsonForResult.getData().toString(), UserMessage.class);
                            application.setName(userMessage.getName());
                            application.setGender(userMessage.getGender());
                            application.setAssistant(userMessage.getAssistant());
                            application.setBirthday(userMessage.getBirthday());
                            application.setCity(userMessage.getCity());
                            application.setCounty(userMessage.getCounty());
                            application.setCreateTime(userMessage.getCreateTime());
                            application.setCreateUser(userMessage.getCreateUser());
                            application.setDeptName(userMessage.getDeptName());
                            application.setDeptId(userMessage.getDeptId());
                            application.setId(userMessage.getId());
                            application.setIdNo(userMessage.getIdNo());
                            application.setJoinSuperviseWork(userMessage.getJoinSuperviseWork());
                            application.setMobileActivateStatus(userMessage.getMobileActivateStatus());
                            application.setMobileNo(userMessage.getMobileNo());
                            application.setMobileRegisterStatus(userMessage.getMobileRegisterStatus());
                            application.setOrgId(userMessage.getOrgId());
                            application.setOrgName(userMessage.getOrgName());
                            application.setProvince(userMessage.getProvince());
                            application.setStatus(userMessage.getStatus());
                            application.setSysUserId(userMessage.getSysUserId());
                            application.setUseSystem(userMessage.getUseSystem());
                            application.setLawEnforceNo(userMessage.getLawEnforceNo());
                            application.setOrgLevel(userMessage.getOrgLevel());
                            startActivity(new Intent(context,MainActivity.class));
                            finish();
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
}